const dayjs = require('dayjs');
require('dayjs/locale/zh-cn');
dayjs.locale('zh-cn')
const app = getApp();
Page({
    data: {
        startCode: '',
        endCode: '',
        selectedDate: '',
        moreDates: [],
        scrollTarget: '',
        isLoading: false,
        listDate: [],
        total: 0,
        navigationBar: 0,
        showTime: false,

        // 出发站点
        startStation: [],
        startLeftIndexTpy: 0,
        startRightIdTpy: '',
        startLeftIndex: 0,
        startRightId: '',

        // 到达站点
        endStation: [],
        endLeftIndexTpy: 0,
        endRightIdTpy: '',
        endLeftIndex: 0,
        endRightId: '',
        // 所有时段
        timeFrames: [
            {
                text: '所有时段',
                id: '',
            },
            {
                text: '早上（00:00 - 12:00）',
                id: "morning",
            },
            {
                text: '下午（12:00 - 18:00）',
                id: "afternoon",
            },
            {
                text: '晚上（18:00 - 24:00）',
                id: "night",
            }
        ],
        timeSelectTpy: '',
        timeSelect: '',
        // 车次排序
        carSorts: [
            {
                text: '价格优先',
                id: 2,
            },
            {
                text: '时间优先',
                id: 1,
            },
        ],
        carSortSelectTpy: 2,
        carSortSelect: 2,

    },

    onLoad: function (options) {
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('acceptDataFromHomePage', (data) => {
            const { start, end, dateTime } = data;
            const systemInfo = wx.getSystemInfoSync();
            const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
            this.setData({
                startCode: start,
                endCode: end,
                selectedDate: dateTime,
                navigationBar: (menuButtonInfo.top - (systemInfo?.statusBarHeight || 0)) * 2 + menuButtonInfo.height,
            });
            this.initDates(dateTime);
            this.queryTripList();
            this.querySiteList(start, end);
        });
    },


    // 初始化日期
    initDates: function (dateTime) {
        const today = dayjs().startOf('day');
        const selectedDate = dayjs(dateTime).startOf('day');

        const diffDays = selectedDate.diff(today, 'day');

        const dayCount = Math.max(20, diffDays + 1);

        const moreDates = [];
        for (let i = 0; i < dayCount; i++) {
            const futureDate = today.add(i, 'day');
            moreDates.push({
                date: futureDate.format('YYYY-MM-DD'),
                dateSimple: futureDate.format('MM-DD'),
                weekday: i === 0 ? '今天' : futureDate.format('ddd'),
                day: futureDate.format('DD')
            });
        }

        this.setData({
            moreDates: moreDates,
            scrollTarget: `date-${dateTime}`
        });
    },

    // 查询车次列表
    queryTripList: async function () {
        try {
            this.setData({ isLoading: true });
            const res = await app.request({
                url: '/sitebus/line/get_line_class_days',
                data: {
                    "date": this.data.selectedDate,
                    "start_citycode": this.data.startCode,
                    "end_citycode": this.data.endCode,
                    "start_gid": this.data.startRightId,
                    "end_gid": this.data.endRightId,
                    "line_gids": '',
                    "time_period": this.data.timeSelect,
                    "orderby": this.data.carSortSelect,
                    "page": 1,
                }
            });
            this.setData({
                listDate: res.data.list,
                total: res.data.total,
            });
        } catch (err) {
            wx.showToast({
                title: err.message || '加载失败',
                icon: 'none'
            });
        } finally {
            this.setData({ isLoading: false });
        }
    },

    querySiteList: async function (start, end) {
        try {
            const res1 = await app.request({
                url: '/sitebus/station/get_stations',
                data: { "type": 1, "citycode": start }
            });
            const res2 = await app.request({
                url: '/sitebus/station/get_stations',
                data: { "type": 2, "citycode": end }
            });
            this.setData({
                startStation: res1.data,
                endStation: res2.data,
            });
        } catch (err) {
            wx.showToast({
                title: err.message || '加载失败',
                icon: 'none'
            });
        } finally {
        }
    },

    onTimeShow() {
        this.setData({ showTime: true });
    },
    onTimeClose() {
        this.setData({ showTime: false });
    },
    onTimeConfirm: function (event) {
        let date = dayjs(event.detail).format('YYYY-MM-DD');
        this.setData({
            showTime: false,
            selectedDate: date,
        });
        this.initDates(date);
        this.queryTripList();
    },

    onStartClose() {
        this.setData({
            startLeftIndexTpy: this.data.startLeftIndex,
            startRightIdTpy: this.data.startRightId
        });
    },
    onStartClickNav({ detail = {} }) {
        this.setData({
            startLeftIndexTpy: detail.index || 0,
        });
    },
    onStartClickItem({ detail = {} }) {
        const activeId = this.data.startRightIdTpy === detail.id ? null : detail.id;
        this.setData({ startRightIdTpy: activeId });
    },
    clearStart: function () {
        this.setData({
            startLeftIndexTpy: 0,
            startRightIdTpy: '',
        });
    },
    confirmStart: function () {
        this.setData({
            startLeftIndex: this.data.startLeftIndexTpy,
            startRightId: this.data.startRightIdTpy
        });
        this.selectComponent('#item-start').toggle();
        this.queryTripList();
    },


    onEndClose() {
        this.setData({
            endLeftIndexTpy: this.data.endLeftIndex,
            endRightIdTpy: this.data.endRightId
        });
    },
    onEndClickNav({ detail = {} }) {
        this.setData({
            endLeftIndexTpy: detail.index || 0,
        });
    },
    onEndClickItem({ detail = {} }) {
        const activeId = this.data.endRightIdTpy === detail.id ? null : detail.id;
        this.setData({ endRightIdTpy: activeId });
    },
    clearEnd: function () {
        this.setData({
            endLeftIndexTpy: 0,
            endRightIdTpy: '',
        });
    },
    confirmEnd: function () {
        this.setData({
            endLeftIndex: this.data.endLeftIndexTpy,
            endRightId: this.data.endRightIdTpy
        });
        this.selectComponent('#item-end').toggle();
        this.queryTripList();
    },

    onSelectDate: function (event) {
        const selectedDate = event.currentTarget.dataset.date;
        this.setData({
            selectedDate: selectedDate,
        });
        this.queryTripList();
    },
    toTripDetail: function (event) {
        const item = event.currentTarget.dataset.date;
        const gid = item.gid;
        wx.navigateTo({
            url: `/pages/sitebus/trip/trip-detail`,
            success: function (res) {
                res.eventChannel.emit('acceptDataFromHomePage', {
                    gid: gid
                });
            }
        });
    },

    onItemTimeClose: function () {
        this.setData({
            timeSelectTpy: this.data.timeSelect,
        });
    },

    onTimeFrameClick: function (event) {
        const { name } = event.currentTarget.dataset;
        this.setData({
            timeSelectTpy: name,
        });
    },
    clearTime: function (event) {
        this.setData({
            timeSelectTpy: '',
        })
    }, confirmTime: function () {
        this.setData({
            timeSelect: this.data.timeSelectTpy,
        })
        this.selectComponent('#item-time').toggle();
        this.queryTripList();
    },


    onItemCarClose: function () {
        this.setData({
            carSortSelectTpy: this.data.carSortSelect,
        });
    },

    onCarFrameClick: function (event) {
        const { name } = event.currentTarget.dataset;
        this.setData({
            carSortSelectTpy: name,
        });
    },
    clearCar: function (event) {
        this.setData({
            carSortSelectTpy: '',
        })
    },
    confirmCar: function () {
        this.setData({
            carSortSelect: this.data.carSortSelectTpy,
        })
        this.selectComponent('#item-car').toggle();
        this.queryTripList();
    },


});